<template>
  <div class="drug-manage">
    <!-- 查询表单 -->
    <el-form :inline="true" size="small" class="search-form">
      <el-form-item label="药品编码">
        <el-input v-model="searchForm.code" placeholder="请输入" clearable @input="debouncedFetchData"></el-input>
      </el-form-item>
      <el-form-item label="药品名称">
        <el-input v-model="searchForm.medicineName" placeholder="请输入" clearable @input="debouncedFetchData"></el-input>
      </el-form-item>
      <el-form-item label="药品类型">
        <el-select v-model="searchForm.isPrescription" placeholder="请选择" clearable @change="debouncedFetchData">
          <el-option label="全部" :value="''"></el-option>
          <el-option label="处方药" :value="1"></el-option>
          <el-option label="非处方药" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择" clearable @change="debouncedFetchData">
          <el-option label="全部" value=""></el-option>
          <el-option label="上架" value="1"></el-option>
          <el-option label="下架" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            clearable
            @change="debouncedFetchData"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onAdd">+新建药品</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="code" label="药品编码" width="100"></el-table-column>
      <el-table-column prop="medicineName" label="药品名称" width="120"></el-table-column>
      <el-table-column prop="specification" label="规格" width="100"></el-table-column>
      <el-table-column prop="categoryName" label="药品分类" width="100"></el-table-column>
      <el-table-column prop="pharmacyName" label="药房" width="100"></el-table-column>
      <el-table-column prop="price" label="单价" width="80"></el-table-column>
      <el-table-column prop="dosageForm" label="剂型" width="80"></el-table-column>
      <el-table-column prop="isPrescription" label="处方药">
        <template slot-scope="scope">
          <span>{{ scope.row.isPrescription === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="manufacturer" label="生产厂家" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.status === 1 ? '上架' : '下架' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="160"></el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" width="160"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-link type="primary" @click="onEdit(scope.row)">编辑</el-link>
          <el-link type="danger" @click="onDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" style="margin-top: 20px; text-align: right;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
      >
      </el-pagination>
    </div>

    <!-- 新增药品弹框 -->
    <el-dialog
        title="新建药品"
        :visible.sync="addDialogVisible"
        width="600px"
        @close="addDialogVisible = false"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="药品编码" prop="code">
          <el-input v-model="addForm.code"></el-input>
        </el-form-item>
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="addForm.medicineName"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="addForm.specification"></el-input>
        </el-form-item>
        <el-form-item label="药品分类" prop="medicinesCategoryId">
          <el-select v-model="addForm.medicinesCategoryId" placeholder="请选择">
            <el-option
                v-for="item in categoryList"
                :key="item.category_id"
                :label="item.category_name"
                :value="item.category_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药房" prop="pharmacyId">
          <el-select v-model="addForm.pharmacyId" placeholder="请选择">
            <el-option
                v-for="item in pharmacyList"
                :key="item.pharmacy_id"
                :label="item.pharmacy_name"
                :value="item.pharmacy_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="addForm.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="剂型" prop="dosageForm">
          <el-input v-model="addForm.dosageForm"></el-input>
        </el-form-item>
        <el-form-item label="处方药" prop="isPrescription">
          <el-select v-model="addForm.isPrescription" placeholder="请选择">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="addForm.manufacturer"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status">
            <el-option label="上架" :value="1"></el-option>
            <el-option label="下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑药品弹框 -->
    <el-dialog
        title="编辑药品"
        :visible.sync="editDialogVisible"
        width="600px"
        @close="editDialogVisible = false"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
        <el-form-item label="药品编码" prop="code">
          <el-input v-model="editForm.code"></el-input>
        </el-form-item>
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="editForm.medicineName"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="editForm.specification"></el-input>
        </el-form-item>
        <el-form-item label="药品分类" prop="medicinesCategoryId">
          <el-select v-model="editForm.medicinesCategoryId" placeholder="请选择">
            <el-option
                v-for="item in categoryList"
                :key="item.category_id"
                :label="item.category_name"
                :value="item.category_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药房" prop="pharmacyId">
          <el-select v-model="editForm.pharmacyId" placeholder="请选择">
            <el-option
                v-for="item in pharmacyList"
                :key="item.pharmacy_id"
                :label="item.pharmacy_name"
                :value="item.pharmacy_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="editForm.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="剂型" prop="dosageForm">
          <el-input v-model="editForm.dosageForm"></el-input>
        </el-form-item>
        <el-form-item label="处方药" prop="isPrescription">
          <el-select v-model="editForm.isPrescription" placeholder="请选择">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="editForm.manufacturer"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option label="上架" :value="1"></el-option>
            <el-option label="下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { debounce } from 'lodash'
// 页面名称：药品管理
export default {
  name: 'DrugManage',
  data() {
    return {
      searchForm: {
        code: '',
        medicineName: '',
        isPrescription: '',
        status: '',
        dateRange: []
      },
      tableData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      addDialogVisible: false,
      addForm: {
        code: '',
        medicineName: '',
        specification: '',
        medicinesCategoryId: '',
        pharmacyId: '',
        price: '',
        dosageForm: '',
        isPrescription: '',
        manufacturer: '',
        status: 1
      },
      addFormRules: {
        code: [{ required: true, message: '请输入药品编码', trigger: 'blur' }],
        medicineName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
        // 其他字段校验可按需添加
      },
      categoryList: [],
      pharmacyList: [],
      editDialogVisible: false,
      editForm: {
        medicineId: '',
        code: '',
        medicineName: '',
        specification: '',
        medicinesCategoryId: '',
        pharmacyId: '',
        price: '',
        dosageForm: '',
        isPrescription: '',
        manufacturer: '',
        status: 1
      },
      editFormRules: {
        code: [{ required: true, message: '请输入药品编码', trigger: 'blur' }],
        medicineName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
        // 其他校验可按需添加
      },
    }
  },
  methods: {
    // 查询药品列表
    async fetchData() {
      this.loading = true
      try {
        const params = {
          code: this.searchForm.code,
          medicineName: this.searchForm.medicineName,
          isPrescription: this.searchForm.isPrescription === '' ? undefined : Number(this.searchForm.isPrescription),
          status: this.searchForm.status === '' ? undefined : Number(this.searchForm.status),
          startTime: this.searchForm.dateRange && this.searchForm.dateRange[0] ? this.searchForm.dateRange[0] : '',
          endTime: this.searchForm.dateRange && this.searchForm.dateRange[1] ? this.searchForm.dateRange[1] : '',
          pageNum: this.pagination.page,
          pageSize: this.pagination.pageSize
        }
        const { data } = await axios.get('/medicines/list', { params })
        this.tableData = data.data || [];
        this.pagination.total = data.total
        // 自动生成药品分类和药房下拉选项
        const categories = {};
        const pharmacies = {};
        (this.tableData || []).forEach(item => {
          if (item.medicinesCategoryId && item.categoryName) {
            categories[item.medicinesCategoryId] = item.categoryName;
          }
          if (item.pharmacyId && item.pharmacyName) {
            pharmacies[item.pharmacyId] = item.pharmacyName;
          }
        });
        this.categoryList = Object.keys(categories).map(id => ({
          category_id: id,
          category_name: categories[id]
        }));
        this.pharmacyList = Object.keys(pharmacies).map(id => ({
          pharmacy_id: id,
          pharmacy_name: pharmacies[id]
        }));
      } finally {
        this.loading = false
      }
    },
    onSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    onReset() {
      this.searchForm = {
        code: '',
        medicineName: '',
        isPrescription: '',
        status: '',
        dateRange: []
      }
      this.pagination.page = 1
      this.fetchData()
    },
    onAdd() {
      this.addDialogVisible = true;
      // 清空表单
      this.$nextTick(() => {
        if (this.$refs.addForm) this.$refs.addForm.resetFields();
      });
    },
    async onDelete(row) {
      await axios.delete(`/medicines/delete/${row.medicineId}`)
      this.$message.success('删除成功')
      this.fetchData()
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.pagination.page = page
      this.fetchData()
    },
    submitAddForm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          await axios.post('/medicines/add', this.addForm);
          this.$message.success('新增成功');
          this.addDialogVisible = false;
          this.fetchData();
        }
      });
    },
    async onEdit(row) {
      const { data } = await axios.get(`/medicines/detail/${row.medicineId}`);
      this.editForm = {
        medicineId: data.medicineId,
        code: data.code || '',
        medicineName: data.medicineName || '',
        specification: data.specification || '',
        medicinesCategoryId: data.medicinesCategoryId !== undefined && data.medicinesCategoryId !== null ? String(data.medicinesCategoryId) : '',
        pharmacyId: data.pharmacyId !== undefined && data.pharmacyId !== null ? String(data.pharmacyId) : '',
        price: data.price !== undefined && data.price !== null ? data.price : '',
        dosageForm: data.dosageForm || '',
        isPrescription: data.isPrescription === '' || data.isPrescription === null || data.isPrescription === undefined
            ? ''
            : (typeof data.isPrescription === 'boolean'
                ? (data.isPrescription ? 1 : 0)
                : Number(data.isPrescription)),
        manufacturer: data.manufacturer || '',
        status: data.status === '' || data.status === null || data.status === undefined
            ? 1
            : Number(data.status)
      };
      this.editDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.editForm) this.$refs.editForm.resetFields();
      });
    },
    submitEditForm() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          await axios.post('/medicines/edit', this.editForm);
          this.$message.success('编辑成功');
          await this.fetchData();
          this.editDialogVisible = false;
        }
      });
    },
  },
  created() {
    this.debouncedFetchData = debounce(() => {
      this.pagination.page = 1
      this.fetchData()
    }, 400)
  },
  mounted() {
    this.fetchData();
  }
}
</script>

<style scoped>
.drug-manage {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 32px 0 0 0;
}
.search-form {
  background: #fff;
  padding: 24px 24px 0 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.search-form .el-form-item {
  margin-right: 24px;
  margin-bottom: 16px;
}
.el-button,
.el-link {
  border-radius: 4px;
  font-size: 14px;
}
.el-button[type="primary"] {
  background: #3a8ee6;
  border-color: #3a8ee6;
}
.el-button {
  background: #f4f4f5;
  color: #606266;
  border: 1px solid #dcdfe6;
}
.el-table {
  background: #fff;
  border-radius: 8px;
  font-size: 14px;
  color: #303133;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}
.el-table th {
  background: #f5f7fa;
  font-weight: bold;
  color: #303133;
}
.el-table td {
  color: #303133;
}
.el-table .el-link[type="primary"] {
  color: #3a8ee6;
}
.el-table .el-link[type="danger"] {
  color: #f56c6c;
}
.el-pagination {
  margin: 24px 0 0 0;
  text-align: center;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
}
.el-pagination .el-pager li.active {
  background: #3a8ee6;
  color: #fff;
  border-color: #3a8ee6;
}
</style>